import api from "@/api/auth";
import { PcCookie, Key } from "@/utils/cookie.js";

const state = {
    userInfo: PcCookie.get(Key.userInfoKey) ? JSON.parse(PcCookie.get(Key.userInfoKey)) : null,
    refreshToken: PcCookie.get(Key.refreshTokenKey), //访问令牌
    accessToken: PcCookie.get(Key.accessTokenKey), //刷新令牌，当访问过期时用到获取新的令牌
}
const mutations = {
    //赋值用户状态
    SET_USER_STATE(state, data) {

        state.userInfo = data.userInfo
        state.refreshToken = data.refresh_token
        state.accessToken = data.access_token
            //存入cookie

        PcCookie.set(Key.userInfoKey, data.userInfo)
        PcCookie.set(Key.accessTokenKey, data.access_token)
        PcCookie.set(Key.refreshTokenKey, data.refresh_token)

    },
    //重置状态
    RESET_USER_STATE(state) {
        state.userInfo = null
        state.refreshToken = null
        state.accessToken = null

        //移除cookie的数据
        PcCookie.remove(Key.userInfoKey)
        PcCookie.remove(Key.refreshTokenKey)
        PcCookie.remove(Key.accessTokenKey)

    }
}

const actions = {
    UserLogin({ commit }, userData) {
        const { username, password } = userData
        return new Promise((resolve, reject) => {
            api.login({ username: username.trim(), password: password }).then(res => {

                if (res.code === 20000) {
                    commit('SET_USER_STATE', res.data)
                }
                resolve(res) //正常响应钩子
            }).catch(error => {
                commit('RESET_USER_STATE')
                reject(error)
            })
        })

    }
}

export default {
    state,
    mutations,
    actions
}